package Exception;

import Utils.ResponseData;
import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Author: liujh
 * @Date:
 * @UpdateUser: liujh
 * @Date: 2020/09/09$ 16:15$
 * @UpdateRemark:
 * @Version: 1.0
 */

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    /**
     * 授权异常
     *
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public ResponseData defaultAuthorizedExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        return ResponseData.error("未授权");
    }

    /**
     * 认证异常处理
     *
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseBody
    public ResponseData defaultAuthenticatedExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {

        return ResponseData.error("未认证");
    }


    @ExceptionHandler(value = KaptchaException.class)
    @ResponseBody
    public String kaptchaExceptionHandler(KaptchaException kaptchaException) {
        if (kaptchaException instanceof KaptchaIncorrectException) {
            return "验证码不正确";
        } else if (kaptchaException instanceof KaptchaNotFoundException) {
            return "验证码未找到";
        } else if (kaptchaException instanceof KaptchaTimeoutException) {
            return "验证码过期";
        } else {
            return "验证码渲染失败";
        }

    }



}
